import { _decorator, Component, misc, Node, tween, v3, Vec3 } from 'cc';
import { EnemyLayers } from './EnemyLayers';
import { BulletType } from './Configs';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Component {
    private _EnemyLayers: EnemyLayers = null;
    private _enemyGun: Node = null
    get enemyGun() {
        if (!this._enemyGun) {
            this._enemyGun = this.node.getChildByName("EnemyGun");
        }
        return this._enemyGun;
    }
    oninit(enemyLayers: EnemyLayers) {
        this._EnemyLayers = enemyLayers;
        //设置敌人的高度为[270,600]
        let minHeight = 300;
        let maxHeight = 600;
        let y = Math.random() * (maxHeight - minHeight) + minHeight;
        tween(this.node)
            .by(1, { position: v3(0, y, 0) })
            .call(() => {
                this._EnemyLayers.sendMsg("changeClickState", "PlayerLayers", true);
            })
            .start()
    }

    death() {
        tween(this.node)
            .to(0.5, { position: v3(this.node.position.x, 0, 0) })
            .call(() => {
                this.node.destroy();
            })
            .start(0)
    }


    fire(player: Node) {
        let fireNode = this.enemyGun.getChildByName("FireNode");
        let enemyGunWorldPos = this.enemyGun.worldPosition;
        let playerWorldPos = player.worldPosition;
        //方向向量 被指向的对象减去指向的对象
        let deltaPos = playerWorldPos.subtract(enemyGunWorldPos).normalize();
        let radians = Vec3.signedAngle(v3(-1, 0, 0), deltaPos, v3(0, 0, 1));
        let degree = misc.radiansToDegrees(radians);
        tween(this.enemyGun)
            .to(0.5, { angle: -degree })
            .call(() => {
                let dir = v3();
                Vec3.rotateZ(dir, v3(-1, 0, 0), v3(0, 0, 1), radians);
                this._EnemyLayers.sendMsg("addBullet", "BulletLayers", fireNode.worldPosition, dir, BulletType.Enemy, "Enemy");
            })
            .to(0.5, { angle: 0 })
            .start();


    }
}


